let _Vue = null
class VueRouter {
  static install(Vue) {
    if(VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    _Vue = Vue
    _Vue.mixin({
      beforeCreate() {
        // console.log(this.$options)
        if(this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      }
    })
  }

  constructor(options) {
    this.options = options
    this.routeMap = {}
    let href = window.location.href
    const index = href.indexOf('#')
    if (index < 0) {//补足路径中的#/
      href = `${href.replace(/\/$/, '')}#/`
      window.location.href = href
    } else {
      href = href.slice(index+1)
      if(!href) window.location.href = href + '/'
    }
    this.data = _Vue.observable({
      current: href ? href : '/'
    })
    this.init()
  }

  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }

  createRouteMap() {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    });
  }

  initComponent(Vue) {
    const _self = this
    Vue.component("router-link", {
      props: {
        to: String
      },
      render(h) {
        return h("a", {
          attrs: {
            href: `#/${this.to.replace(/^\//, '')}`,
            class: this.to === _self.data.current ? 'router-link-exact-active' : ''
          }
        }, [this.$slots.default])
      }
    })
    Vue.component("router-view", {
      render(h) {
        let comp = _self.routeMap[_self.data.current]
        if(!comp) comp = _self.routeMap['*']
        return h(comp)
      }
    })
  }

  initEvent() {
    window.addEventListener("hashchange", (e) => {
      let href = window.location.href
      const index = href.indexOf('#')
      if (index < 0) {
        href = `${href.replace(/\/$/, '')}#/`
      }
      href = href.slice(index+1)
      this.data.current = href ? href : '/'
    })
  }
}
export default VueRouter